package com.neutech.servlet;


import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter(urlPatterns = "/f")
public class LoggingFilter implements Filter {
    private static final Logger logger =
            Logger.getLogger(LoggingFilter.class.getName());
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
//设置请求信息的字符编码（必须在使用request之前进行设置）
        request.setCharacterEncoding("utf-8");
//使客户端浏览器并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
        response.setContentType("text/html;charset=utf-8");
//设置响应信息的字符编码（必须在创建响应输出流之前进行设置）
        response.setCharacterEncoding("utf-8");
        String requestMethod = httpRequest.getMethod();
        String requestURI = httpRequest.getRequestURI();
        HttpSession session = httpRequest.getSession(false);
        String sessionId = session != null ? session.getId() : "N/A";
        long startTime = System.currentTimeMillis();
        logger.info("请求开始: " + requestMethod + " " +
                requestURI + " SessionId: " +sessionId);
                chain.doFilter(request, response);
        long endTime = System.currentTimeMillis();
        logger.info("请求完成: " + requestMethod + " "
                + requestURI + " SessionId: " + sessionId + " 时间: "
                + (endTime - startTime) + " ms");
    }
    @Override
    public void destroy() {
// Clean up resources
    }
}

